package com.example.fresh_market.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.example.fresh_market.R;
import com.example.fresh_market.request.ProductInfo;
import com.example.fresh_market.utils.HttpUtil;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class CreateOrderAdapter extends RecyclerView.Adapter<CreateOrderAdapter.ViewHolder> {

    private final ArrayList<ProductInfo> productInfos;

    public CreateOrderAdapter(ArrayList<ProductInfo> productInfos) {
        this.productInfos = productInfos;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = ViewGroup.inflate(viewGroup.getContext(), R.layout.create_order_item, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        ProductInfo productInfo = getItem(i);
        viewHolder.productName.setText(productInfo.getProductName());
        viewHolder.productPrice.setText(String.format("单价：¥%s", productInfo.getPrice()));
        viewHolder.productNum.setText(String.format("数量：%s", productInfo.getQuantity()));
        if (StringUtils.isNotBlank(productInfo.getProductImg())) {
            HttpUtil.loadImage(viewHolder.productImage, productInfo.getProductImg(), new RequestOptions().override(120, 120));
        }
    }

    public ProductInfo getItem(int position) {
        return productInfos.get(position);
    }

    @Override
    public int getItemCount() {
        return productInfos.size();
    }

    public void setData(List<ProductInfo> list) {
        productInfos.clear();
        productInfos.addAll(list);
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final ImageView productImage;
        private final TextView productName;
        private final TextView productPrice;
        private final TextView productNum;

        public ViewHolder(@NonNull View view) {
            super(view);
            productImage = view.findViewById(R.id.create_order_item_image);
            productName = view.findViewById(R.id.create_order_item_name);
            productPrice = view.findViewById(R.id.create_order_item_price);
            productNum = view.findViewById(R.id.create_order_item_num);
        }
    }
}
